#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
using namespace std;

int main(int argc, char** argv, char** env){
  pid_t id = fork();
  if(id == 0)
  {
    //子进程执行流
    cout << "I'm child process! child_pid:" << getpid() << endl;
    //execv("/home/zty/code/Linux/20230721/test", argv);
    //char *const argv[] = {(char*)"test", (char*)"-e", NULL};
    //char *const _env[] = {(char*)"MYENV=122", NULL};
    //execve("./test", argv, _env);
    char *const argv[] = {(char*)"ls", (char*)"-a",(char*)"-l", NULL};
    execve("ls", argv, env);
    return 1; 
  }
  else if(id > 0)
  {
    //父进程执行流
    int status = 0;
    pid_t ret = waitpid(id, &status, 0);
    if(ret > 0)
    {
      if(WIFEXITED(status))
      {
        cout << "子进程正常退出！child_pid:" << ret;
        cout << " exit_code:" << WEXITSTATUS(status) << endl;
      }
      else{
        cout << "子进程崩溃！child_pid:" << ret;
        cout << " exit_signal:" << (status & 0x7F) << endl;
      }
    }
    else if(ret == -1)
    {
      cout << "等待子进程失败！" << endl;
    }
  }
  else{
    perror("子进程创建失败！");
    return 1;
  }
}

//int main(){
//  cout << "当前进程的开始代码！" << endl;
//  execl("/usr/bin/ls", "ls", "-a", "-l", "--color=auto", NULL);
//  cout << "当前进程的结束代码！" << endl;
//}
